
package com.joolun.cloud.weixin.admin.controller;

import cn.binarywang.wx.miniapp.api.WxMaCodeService;
import cn.binarywang.wx.miniapp.bean.code.WxMaCodeAuditStatus;
import cn.binarywang.wx.miniapp.bean.code.WxMaCodeSubmitAuditRequest;
import cn.binarywang.wx.miniapp.constant.WxMaApiUrlConstants;
import cn.hutool.core.codec.Base64;
import com.joolun.cloud.common.core.util.R;
import com.joolun.cloud.weixin.admin.config.open.WxOpenConfiguration;
import com.joolun.cloud.weixin.admin.service.WxmaCodeAuditService;
import com.joolun.cloud.weixin.common.constant.WxReturnCode;
import com.joolun.cloud.weixin.common.entity.WxMaCodeCommitRequest;
import com.joolun.cloud.weixin.common.entity.WxmaCodeAudit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.open.api.WxOpenFastMaService;
import me.chanjar.weixin.open.bean.WxOpenMaCodeTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 小程序代码管理
 *
 * @author www.joolun.com
 * @date 202-01-25 15:39:39
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/open/ma/code")
@Api(value = "openmacode", tags = "小程序代码管理")
public class WxMaCodeTemplateController {

	private final WxmaCodeAuditService wxmaCodeAuditService;

	/**
	* 获取代码模板列表
	* @return
	*/
	@ApiOperation(value = "获取代码模板列表")
	@GetMapping("/template/list")
	@PreAuthorize("@ato.hasAuthority('wxma:code:index')")
	public R getCodeTemplateList() {
		try {
			List<WxOpenMaCodeTemplate> list = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getTemplateList();
			return R.ok(list);
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.error("getCodeTemplateList：", e);
			return WxReturnCode.wxErrorExceptionHandler(e);
		}

	}

	/**
	 * 上传小程序代码
	 * @return
	 */
	@ApiOperation(value = "上传小程序代码")
	@PostMapping("/{appId}/commit")
	@PreAuthorize("@ato.hasAuthority('wxma:code:index')")
	public R codeCommit(@PathVariable("appId") String appId, @RequestBody WxMaCodeCommitRequest commitRequest) {
		try {
//			WxMaCodeService wxMaCodeService = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxFastMaServiceByAppid(appId).getCodeService();
			//上传小程序代码
//			wxMaCodeService.commit(commitRequest);
			//上传小程序代码
			WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxFastMaServiceByAppid(appId).post(WxMaApiUrlConstants.Code.COMMIT_URL,commitRequest.toJson());
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.error("codeCommit：", e);
			return WxReturnCode.wxErrorExceptionHandler(e);
		}
		return R.ok();
	}

	/**
	 * 获取已上传的代码的页面列表
	 * @return
	 */
	@ApiOperation(value = "获取已上传的代码的页面列表")
	@GetMapping("/{appId}/page")
	@PreAuthorize("@ato.hasAuthority('wxma:code:index')")
	public R getPage(@PathVariable("appId") String appId) {
		try {
			WxOpenFastMaService wxOpenFastMaService = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxFastMaServiceByAppid(appId);
			return R.ok(wxOpenFastMaService.getCodeService().getPage());
		} catch (WxErrorException e) {
			if(e.getError().getErrorCode() == 86001){
				return R.ok(new ArrayList<>());
			}
			e.printStackTrace();
			log.error("getPage：", e);
			return WxReturnCode.wxErrorExceptionHandler(e);
		}
	}

	/**
	 * 获取体验版二维码
	 * @return
	 */
	@ApiOperation(value = "获取体验版二维码")
	@GetMapping("/{appId}/qrcode")
	@PreAuthorize("@ato.hasAuthority('wxma:code:index')")
	public R getQrCode(@PathVariable("appId") String appId){
		try {
			WxOpenFastMaService wxOpenFastMaService = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxFastMaServiceByAppid(appId);
			return R.ok(wxOpenFastMaService.getCodeService().getQrCode(null));
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.error("getQrcode：", e);
			return WxReturnCode.wxErrorExceptionHandler(e);
		}
	}

	/**
	 * 提交审核
	 * @return
	 */
	@ApiOperation(value = "提交审核")
	@PostMapping("/{appId}/submit")
	@PreAuthorize("@ato.hasAuthority('wxma:code:index')")
	public R codeSubmit(@PathVariable("appId") String appId) {
		try {
			WxMaCodeService wxMaCodeService = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxFastMaServiceByAppid(appId).getCodeService();
			WxMaCodeSubmitAuditRequest auditRequest = new WxMaCodeSubmitAuditRequest();
			//提交审核
			wxMaCodeService.submitAudit(auditRequest);
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.error("codeSubmit：", e);
			return WxReturnCode.wxErrorExceptionHandler(e);
		}
		return R.ok();
	}

	/**
	 * 查询最新一次提交的审核状态
	 * @return
	 */
	@ApiOperation(value = "查询最新一次提交的审核状态")
	@GetMapping("/{appId}/auditstatus")
	@PreAuthorize("@ato.hasAuthority('wxma:code:index')")
	public R getLatestAuditstatus(@PathVariable("appId") String appId) {
		WxMaCodeAuditStatus wxMaCodeAuditStatus = new WxMaCodeAuditStatus();
		try {
			WxOpenFastMaService wxOpenFastMaService = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxFastMaServiceByAppid(appId);
			wxMaCodeAuditStatus =  wxOpenFastMaService.getCodeService().getLatestAuditStatus();
		} catch (WxErrorException e) {
			if(e.getError().getErrorCode() == 85058){
				return R.ok(wxMaCodeAuditStatus);
			}
			e.printStackTrace();
			log.error("getLatestAuditstatus：", e);
			return WxReturnCode.wxErrorExceptionHandler(e);
		}
		return R.ok(wxMaCodeAuditStatus);
	}

	/**
	 * 审核撤回
	 * @return
	 */
	@ApiOperation(value = "审核撤回")
	@GetMapping("/{appId}/undocodeaudit")
	@PreAuthorize("@ato.hasAuthority('wxma:code:index')")
	public R undoCodeAudit(@PathVariable("appId") String appId) {
		try {
			WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxFastMaServiceByAppid(appId).getCodeService().undoCodeAudit();
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.error("undoCodeAudit：", e);
			return WxReturnCode.wxErrorExceptionHandler(e);
		}
		return R.ok();
	}

	/**
	 * 发布已通过审核的小程序
	 * @return
	 */
	@ApiOperation(value = "发布已通过审核的小程序")
	@PostMapping("/{appId}/{auditId}/release")
	@PreAuthorize("@ato.hasAuthority('wxma:code:index')")
	public R codeRelease(@PathVariable("appId") String appId, @PathVariable("auditId") String auditId) {
		try {
			WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxFastMaServiceByAppid(appId).getCodeService().release();
			WxmaCodeAudit wxmaCodeAudit = new WxmaCodeAudit();
			wxmaCodeAudit.setAppId(appId);
			wxmaCodeAudit.setAuditId(auditId);
			wxmaCodeAuditService.save(wxmaCodeAudit);
		} catch (WxErrorException e) {
			if(e.getError().getErrorCode() == 85052){
				WxmaCodeAudit wxmaCodeAudit = new WxmaCodeAudit();
				wxmaCodeAudit.setAppId(appId);
				wxmaCodeAudit.setAuditId(auditId);
				wxmaCodeAuditService.save(wxmaCodeAudit);
			}
			e.printStackTrace();
			log.error("codeRelease：", e);
			return WxReturnCode.wxErrorExceptionHandler(e);
		}
		return R.ok();
	}

	/**
	 * 获取截图示例
	 * @return
	 */
	@ApiOperation(value = "获取截图示例")
	@GetMapping("/{appId}/screenshot/{mediaId}")
	@PreAuthorize("@ato.hasAuthority('wxma:code:index')")
	public R getScreenShot(@PathVariable("appId") String appId,@PathVariable("mediaId") String mediaId) throws IOException {
		try {
			WxMpMaterialService wxMpMaterialService = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxMpServiceByAppid(appId).getMaterialService();
			InputStream in = wxMpMaterialService.materialImageOrVoiceDownload(mediaId);
			byte[] data = new byte[in.available()];
			in.read(data);
			in.close();
			//对字节数组Base64编码
			Base64 encoder = new Base64();
			//返回Base64编码过的字节数组字符串
			String base64 = encoder.encode(data);
			return R.ok(base64);
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.error("getScreenShot：", e);
			return WxReturnCode.wxErrorExceptionHandler(e);
		}
	}
}
